app.Page = {};

app.Page.common = {
	is : function() {},
	
	init : function() {},
	
	action : function() {},
	
	log : function(id, value) {
		app.UI.setStat(id, value);
	}
};

/**
 * Main page
 */
app.Page.main = $.extend({}, app.Page.common, {
	is : function() {
		return $('#contentselect').size() > 0 && $('#mob').size() > 0;
	},
	
	init : function() {
		if (app.globalAction == app.ACTION_NEW_MOB) {
			$('#mob').val($('#mob option[style]').val()).change();
			
			app.resetAction();
		}
	},
	
	action : function() {
		switch (app.globalAction) {
			case app.ACTION_QUEST_COMPLETE:
				// Select quests
				$('#contentselect').val(5).change();
				break;
			case app.ACTION_TRADESKILL:
				$('#contentselect').val(4).change();
				break;
			default:
				if ($('#battlebutton').val() != 'Submit') {
					document.getElementById('battlebutton').click();
				}
		}
	}
});

/**
 * Fight page
 */
app.Page.fight = $.extend({}, app.Page.common, {
	/**
	 * Check if page matches
	 */
	is : function() {
		return app.Bot.$content.is(':contains("You hit the")');
	},
	
	/**
	 * Initialize page
	 */
	init : function() {
		this.$content = app.Bot.$content;
		
		this.checkResults();
		this.checkLevelUp();
		this.checkLoot();
		this.checkQuestComplete();
	},
	
	/**
	 * Check fight results
	 */
	checkResults : function() {
		if (this.$content.is(':contains("You defeated the")')) {
			this.log('win', ++app.Bot.stats.win);
			
			return true;
		}
		else {
			this.log('loose', ++app.Bot.stats.loose);
			
			return false;
		}
	},
	
	/**
	 * Check if player has levelled up
	 */
	checkLevelUp : function() {
		var $levelup = this.$content.find(':contains("You gained a level")');
		
		if ($levelup.size() > 0) {
			this.log('levels', ++app.Bot.stats.levels);
		}
		
		// If some rune shards found
		if ($levelup.is(':contains("rune shard(s)")')) {
			var value = $levelup.text().replace(/[^\d+]/g, '');
			
			this.log('shards', app.Bot.stats.loot.shards += +value);
		}
	},
	
	/**
	 * Check battle loot
	 */
	checkLoot : function() {
		var $drop = this.$content.find('#drop');
		
		if ($drop.size() < 1) {
			return false;
		}
		
		var details = $('img:first', $drop).attr('src').split('/'),
			lootType = details[2],
			statsMap = ['', 'health', 'attack', 'defence', 'accuracy', 'evasion', 'luck'],
			runesMap = ['', 'minor', 'major', 'ancient'],
			runeLevelMap = ['', 'gray', 'green', 'blue', 'yellow', 'purple', 'red'];
		
		// Do actions depending of loot type
		switch (details[2]) {
			// Stats up
			case 'stats':
				var stat = statsMap[parseInt(details[3])];
				
				this.log(stat, ++app.Bot.stats.attr[stat]);
				break;
			// Rune found
			case 'runes':
				var runeType = runesMap[details[3]]
					runeLevel = runeLevelMap[parseInt(details[4])];
				
				this.log(runeType + runeLevel, ++app.Bot.stats.loot.runes[runeType][runeLevel]);
				
				break;
			// Main loot found or something else
			default:
				var str = $('#drop div:eq(1)').text(),
					pattern = /[\d\,]+/g,
					value = 0,
					match;
				
				while (match = pattern.exec(str)) {
					value += +match.toString().replace(/[^\d]/g, '');
				}
				
				this.log(details[2], app.Bot.stats.loot[details[2]] += value);
		}
	},
	
	/**
	 * Check if player completed the quest
	 */
	checkQuestComplete : function() {
		if (this.$content.is(':contains("You have completed the quest")')) {
			app.globalAction = app.ACTION_QUEST_COMPLETE;
		}
	},
	
	/**
	 * Do action when page is ready to
	 */
	action : function() {
		switch (app.globalAction) {
			case app.ACTION_QUEST_COMPLETE:
				$('input[value="Continue"]').click();
				break;
			default:
				if ($('#battlebutton').val() != 'Submit') {
					document.getElementById('battlebutton').click();
				}
		}
	}
});

/**
 * ReCaptcha page
 * We should stop here - we cannot parse the captcha
 */
app.Page.recaptcha = $.extend({}, app.Page.common, {
	is : function() {
		return $('#recaptcha_div').size() > 0;
	},
	
	init : function() {
		if (webkitNotifications.checkPermission() == 0) {
			webkitNotifications.createNotification('', 'TLR Bot', 'Check the ReCaptcha').show();
		}
	},
	
	action : function() {}
});

/**
 * Quests page
 */
app.Page.quests = $.extend({}, app.Page.common, {
	/*
	 1. Fight page -> click <Continue> button
	 2. Main page -> select value 5 from #contentselect
	 3. Quest page -> click the <Collect Reward From Quest> button
	 4. Quest page -> click the <Generate Quest> button
	 5. Quest page -> select value 1 from #contentselect
	 6. Main page -> find mob in #mob (has "style" attribute), select it and click <Attack> button

	<div class="questdiv">
		You are currently on a quest to kill 7 Small Rat(s).<br><br>
		<span style="color: #22DD22">You have completed your quest!</span><br><br>
		<input type="button" value="Collect Reward From Quest" onclick="completeQuest();">
	</div>

	<div class="success">You have completed the quest!<br><br>+300 Gold</div>
	<div class="questdiv">
		You are not currently on a quest. Once you have completed 10 quests you will be able to choose the range of mobs you want to battle whilst questing but until then they will be chosen for you.<br><br>
		<input type="button" value="Generate Quest" onclick="generateQuest(1);">
	</div>

	<div class="questdiv">You are currently on a quest to collect 6 Gemstone(s) from the Moth.<br><br>You have collected 0 quest items and still have 6 left to find before you complete this quest.</div>
	*/
	is : function() {
		return app.Bot.$content.find('.questdiv').size() > 0;
	},
	
	init : function() {
		if (app.Bot.$content.find('.success').size() > 0 && $('input[value="Collect Reward From Quest"]').size() > 0) {
			this.log('quests', ++app.Bot.stats.quests);
		}
	},
	
	action : function() {
		var $btn;
		
		if (($btn = $('input[value="Collect Reward From Quest"]')) && $btn.size() > 0) {
			$btn.click();
		}
		else if (($btn = $('input[value="Generate Quest"]')) && $btn.size() > 0) {
			$btn.click();
		}
		else {
			app.globalAction = app.ACTION_NEW_MOB;
			$('#contentselect').val(1).change();
		}
	}
});

/**
 * Tradeskills page
 */
app.Page.tradeskill = $.extend({}, app.Page.common, {
	/*
	 1. Main page -> select value 4 from #contentselect
	 2. Tradeskill page -> select mode if needed (click on one of 4 links in $content > table)
	 3. Tradeskills page -> select duration by clicking the link (10 seconds by default, search by link text "for 10 seconds")
	 4. Tradeskill page -> wait for tradeskilling complete, then log the results and click on "Continue" link
	 5. Repeat #2
	 */
	is : function() {
		return app.Bot.$content.find('a:contains("Foraging")').size() > 0;
	},
	
	init : function() {
		var $link = app.Bot.$content.find('a:contains("for 10 seconds"):first');
		
		if ($link.size() > 0) {
			$link.clone().attr('onclick', $link.attr('href').replace('javascript:', '')).attr('href', '#').click().remove();
		}
	},
	
	action : function() {
		if ($('#tsheader:contains("0 attempt(s) remaining!")').size() > 0) {
			setTimeout(function() {
				var $link = app.Bot.$content.find('a:contains("Continue"):first');
				
				if ($link.size() > 0) {
					$link.clone().attr('onclick', $link.attr('href').replace('javascript:', '')).attr('href', '#').click().remove();
				}
			}, 1200);
		}
	}
});

/**
 * Arena page
 */
app.Page.arena = $.extend({}, app.Page.common, {
	/*
	 1. Main page -> select value 10 from #contentselect
	 2. Arena page -> click on any "Join" link
	 3. Arena page -> if we see success message (div.success) then select value 1 from #contentselect
	 */
	is : function() {
		return app.Bot.$content.find('b:contains("PvP Arena")').size() > 0;
	},
	
	init : function() {
		app.Bot.$content.find('a:first:contains("Join")').click();
	},
	
	action : function() {
		if (app.Bot.$content.find('div.success').size() > 0) {
			app.globalAction = app.ACTION_NEW_MOB;
			$('#contentselect').val(1).change();
		}
	}
});
